<?php
/*
Plugin Name: Shopping Cart
Plugin URI: http://wp-jacob.googlecode.com
Description: Implements a Google Checkout shopping cart
Version: 0.2
Author: Jacob Brunson
Author URI: http://jacobbrunson.com
*/

/*  Copyright 2008  Jacob Brunson  (email : wp-jacob.gpl.license@jacobbrunson.com )

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/


// This function tells WP to add a new "meta box"
function shopcart_add_box() 
{
    add_meta_box(
        'shopcartdiv', // id of the <div> we'll add
        'Shopping Cart Information', //title
        'shopcart_cartinfo_box', // callback function that will echo the box content
        'post' // where to add the box: on "post", "page", or "link" page
    );
}

function shopcart_add_post_javascript()
{
    $script_url = WP_PLUGIN_URL.'/'.dirname(plugin_basename(__FILE__)).'/post.js';
    wp_enqueue_script('shopcartpostscript', $script_url);
}

function shopcart_add_options_javascript()
{
    $script_url = WP_PLUGIN_URL.'/'.dirname(plugin_basename(__FILE__)).'/options.js';
    wp_enqueue_script('shopcartoptionsscript', $script_url, array('prototype'));
}

function shopcart_load_options_page()
{
    include_once(WP_PLUGIN_DIR.'/'.dirname(plugin_basename(__FILE__)).'/options.php');
}

function shopcart_save_shipping_options()
{
    if (array_key_exists('shopcart_shipping_method', $_POST)) {
        switch (trim($_POST['shopcart_shipping_method'])) {
            case 'flat':
                $table = array_combine($_POST['shipping_flatrate_country'], $_POST['shipping_flatrate_rate']);
                if (get_option('shopcart_flatrate_table')) {
                    update_option('shopcart_flatrate_table', $table);
                } else {
                    add_option('shopcart_flatrate_table', $table);
                }
                break;

            default:
        }
    }
}

// This function echoes the content of our meta box
function shopcart_cartinfo_box() 
{
    $conditions = array('new', 'used', 'refurbished');
    $edit_post = intval($_GET['post']);
    $price_meta = get_post_meta($edit_post, 'shopcart_price', true);
    $weight_meta = get_post_meta($edit_post, 'shopcart_weight', true);
    $upc = '';
    $image = '';
    $cond = 'new';
    $p = '';
    $w = '';
    $enabled = true && (get_post_meta($edit_post, 'shopcart_enabled', true) == 'true');
    $disabled = $enabled ? '' : 'disabled="disabled"';
    if ($edit_post > 0) {
        if (trim($price_meta) != '') {
            $p = number_format((float)$price_meta, 2);
        }
        if (trim($price_meta) != '') {
            $w = (float)$weight_meta;
        }
        $upc = get_post_meta($edit_post, 'shopcart_upc', true);
        $image = get_post_meta($edit_post, 'shopcart_image', true);
        $condition_meta = get_post_meta($edit_post, 'shopcart_condition', true);
        if (in_array($condition_meta, $conditions)) {
            $cond = $condition_meta;
        }
    }
    echo 'Google Checkout: <select name="shopcart_enabled" onchange="enableCheckout(this.options.selectedIndex==0);">';
    if ($enabled) {
        echo '<option value="true" selected="selected">Enabled</option>
                <option value="false">Disabled</option>';
    } else {
        echo '<option value="true">Enabled</option>
                <option value="false" selected="selected">Disabled</option>';
    }
    echo "</select><br/>
    Price: <input name=\"shopcart_price\" value=\"$p\" $disabled /> ".get_option('shopcart_currency')."<br/>\n
          Weight: <input name=\"shopcart_weight\" value=\"$w\" $disabled /> ".get_option('shopcart_weight_units')."<br/>\n
          UPC Code: <input name=\"shopcart_upc\" value=\"$upc\" $disabled /><br/>\n
          Condition: <select name=\"shopcart_condition\" $disabled>\n";
    foreach ($conditions as $condition) {
        echo "<option value=\"condition\" ";
        if ($condition == $cond) echo 'selected="selected" ';
        echo ">$condition</option>\n";
    }
    echo "</select><br/>";
    echo "Image URI: <input name=\"shopcart_image\" value=\"$image\" $disabled />";
}

// Hook things in, late enough so that add_meta_box() is defined
if (is_admin()) {
    add_action('admin_menu', 'shopcart_add_box');
    add_action('admin_menu', 'shopcart_add_options_page');
    add_action('admin_print_scripts', 'shopcart_add_post_javascript');
}

add_action('save_post', 'shopcart_save_info');
function shopcart_save_info($post_ID)
{
    if ($_POST['shopcart_enabled'] == 'true') {
        if (!add_post_meta($post_ID, 'shopcart_enabled', 'true', true)) {
            update_post_meta($post_ID, 'shopcart_enabled', 'true');
        }

        if (trim($_POST['shopcart_price']) != '') {
            add_post_meta($post_ID, 'shopcart_price', number_format((float)$_POST['shopcart_price'], 2), true)
            or  update_post_meta($post_ID, 'shopcart_price', number_format((float)$_POST['shopcart_price'], 2));
        }

        add_post_meta($post_ID, 'shopcart_weight', (float)$_POST['shopcart_weight'], true)
        or  update_post_meta($post_ID, 'shopcart_weight', (float)$_POST['shopcart_weight']);

        add_post_meta($post_ID, 'shopcart_upc', $_POST['shopcart_upc'], true)
        or  update_post_meta($post_ID, 'shopcart_upc', $_POST['shopcart_upc']);

        add_post_meta($post_ID, 'shopcart_image', $_POST['shopcart_image'], true)
        or update_post_meta($post_ID, 'shopcart_image', $_POST['shopcart_image']);

    } else {
        if (!add_post_meta($post_ID, 'shopcart_enabled', 'false', true)) {
            update_post_meta($post_ID, 'shopcart_enabled', 'false');
        }
    }

}

function echo_shipping_table_data()
{
    if (get_option('shopcart_shipping_method') != 'flat') return;
    $i = 1;
    $s_currency = get_option('shopcart_currency');
    $flatrate_table = get_option('shopcart_flatrate_table');
    $others_exclude = array();
    echo '<form id="googlecart-checkout-config">';
    if (is_array($flatrate_table)) {
        foreach ($flatrate_table as $row_key => $row_data) {
            if ($row_key !== 'all_others') continue;
            $others_exclude[] = $row_key;
            echo "<input type=\"hidden\" name=\"checkout-flow-support.merchant-checkout-flow-support.shipping-methods.flat-rate-shipping-$i.name\" value=\"Shipping to $row_key\"/>";
            echo "<input type=\"hidden\" name=\"checkout-flow-support.merchant-checkout-flow-support.shipping-methods.flat-rate-shipping-$i.price\" value=\"$row_value\"/>";
            echo "<input type=\"hidden\" name=\"checkout-flow-support.merchant-checkout-flow-support.shipping-methods.flat-rate-shipping-$i.price.currency\" value=\"$s_currency\"/>";
            echo "<input type=\"hidden\" name=\"checkout-flow-support.merchant-checkout-flow-support.shipping-methods.flat-rate-shipping-$i.shipping-restrictions.allowed-areas.postal-area-$i.country-code\" value=\"$row_key\"/>";
            $i++;
        }
        echo "<input type=\"hidden\" name=\"checkout-flow-support.merchant-checkout-flow-support.shipping-methods.flat-rate-shipping-$i.name\" value=\"International Shipping\"/>";
        echo "<input type=\"hidden\" name=\"checkout-flow-support.merchant-checkout-flow-support.shipping-methods.flat-rate-shipping-$i.price\" value=\"$row_value\"/>";
        echo "<input type=\"hidden\" name=\"checkout-flow-support.merchant-checkout-flow-support.shipping-methods.flat-rate-shipping-$i.price.currency\" value=\"$s_currency\"/>";
        foreach ($others_exclude as $country_code) {
            echo "<input type=\"hidden\" name=\"checkout-flow-support.merchant-checkout-flow-support.shipping-methods.flat-rate-shipping-$i.shipping-restrictions.excluded-areas.postal-area-$i.country-code\" value=\"$country_code\"/>";
        }
    }
    echo '</form>';
}

add_action('wp_footer', 'shopcart_footer');
function shopcart_footer($post_ID)
{
    $mid = get_option('shopcart_mid');
    $currency_code = "USD";
    $checkout_url = "http://checkout.google.com/seller/gsc/v2/cart.js?mid=";
    $script_src = attribute_escape($checkout_url.$mid);
    $hide_empty_cart = get_option('shopcart_hide_empty_cart');
    if ($hide_empty_cart != 'false') {
      $hide_empty_cart = true;
    }
    $sandbox_mode = get_option('shopcart_sandbox_mode');
    if ($sandbox_mode != 'false') {
        $sanbox_mode = true;
        $sandbox_mid = get_option('shopcart_sandbox_mid');
        $script_src = attribute_escape($checkout_url.$sandbox_mid);
    }

    echo_shipping_table_data();
    
    echo "<script id='googlecart-script' type='text/javascript'";
    echo " src='$script_src'";
    echo " currency='$currency_code'";
    echo " post-cart-to-sandbox='$sandbox_mode'";
    echo " hide-cart-when-empty='$hide_empty_cart'";
    echo '>';
    echo "</script>";
}

function shopcart_add_options_page()
{
    $mypage = add_options_page('Shipping Cart Options', 'Shopping Cart', 8, __FILE__, 'shopcart_load_options_page');
    add_action("admin_print_scripts-$mypage", 'shopcart_add_options_javascript');
}

add_action('the_content', 'append_cart_info');
function append_cart_info($content)
{
    global $post;
    $enabled = true && (get_post_meta($post->ID, 'shopcart_enabled', true) == 'true');
    if ($enabled) {
        $price = get_post_meta($post->ID, 'shopcart_price', true);
        $currency = get_option('shopcart_currency');
        $image = get_post_meta($post->ID, 'shopcart_image', true);
        $out = '<br/>';
        $out .= '<div class="product">';
        $out .= "<input class='product-title' value=\"{$post->post_title}\" type=\"hidden\"/>\n";
        $out .= "Price: <span class='product-price'>$price</span> $currency\n";
        $shipping_mode = get_option('shopcart_shipping_method');
        switch ($shipping_mode) {
            case 'peritem':
                $out .= '<span class="product-shipping-first" style="display:none;">';
                $out .= number_format(floatval(get_option('shopcart_byitemshipping_baserate')) + floatval(get_option('shopcart_byitemshipping_itemrate')), 2);
                $out .= '</span><span class="product-shipping" style="display:none;">';
                $out .= number_format(floatval(get_option('shopcart_byitemshipping_itemrate')), 2);
                $out .= '</span>';
            break;

            case 'byweight':
                $out .= '<span class="product-shipping-first" style="display:none;">';
                $weight_cost = floatval(get_option('shopcart_byitemshipping_itemrate')) * floatval(get_post_meta($post->ID, 'shopcart_weight'));
                $out .= number_format(floatval(get_option('shopcart_byitemshipping_baserate')) + $weight_cost, 2);
                $out .= '</span><span class="product-shipping" style="display:none;">';
                $out .= number_format($weight_cost, 2);
                $out .= '</span>';
            break;

            default:
        }
        $out .= '<div class="googlecart-add-button"></div>';
        $out .= "<input value=\"$image\" class=\"product-image\" type=\"hidden\"/>";
        $out .= '</div>';
        return $content . $out;
    } else {
        return $content;
    }
}

?>